package com.lbb.springboot.auto.util;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.lbb.springboot.auto.util.FormData.FieldData;

public class AutoGenerationSpringMVC {

	static List<FieldData> lf = new ArrayList<FieldData>();
	static String tableName="biu_menu";
	static String className = tableName;
	static String classNameLowerCase = className.toLowerCase();

	static String name=DomysqlBean.toUpperCaseFirstOne(DomysqlBean.replaceLine(className));

	public static void main(String[] args) throws SQLException {
		// String className="Advert";
		lf = DomysqlBean.autoFieldData("biu_menu");
		String iDaoBean = IDaoBean(name);
		String iDaoImplBean = IDaoImplBean(name);
		String iServiceBean = IServiceBean(name);
		String iServiceImplBean = IServiceImplBean(name);
		String controller = controller(name);

		//生成实体类
		DomysqlBean.autoBean("activity_test");
		// 生成controller
	 	saveFile(name + "Controller", controller, "controller");
		// 生成dao
		saveFile("I" + name+ "Dao", iDaoBean, "dao");
		saveFile(name + "Dao", iDaoImplBean, "dao/impl");
		// 生成service
		saveFile("I" + name + "Service", iServiceBean, "service");
		saveFile(name + "Service", iServiceImplBean, "service/impl");

	}

	public static String generateAddText(String className) {
		String addText = "";
		addText += "\r\r\tpublic long add("+className+" "+classNameLowerCase+") {\r";
		addText += "\r\t\t Map<String, Object> valueArgMap = new HashMap<String, Object>();\r";
		for (int i = 0; i < lf.size(); i++) {
			FieldData fieldData = lf.get(i);
			if(!"id".equals(fieldData.getField())){
				addText += "\t\t valueArgMap.put(\""+fieldData.getField()+"\", "+classNameLowerCase+".get"+DomysqlBean.replaceLine(DomysqlBean.toUpperCaseFirstOne(fieldData.getField()))+"());\r";
			}
		}
		addText += "\t\t return insert(\""+classNameLowerCase+"\", valueArgMap);\r";
		addText += "\t}\r";
		System.out.println(addText);
		return addText;
	}

	public static String generateUpdText(String className)  {
		String updText = "";
		updText += "\r\tpublic long upd("+className+" "+classNameLowerCase+") {\r";
		updText += "\r\t\t Map<String, Object> valueArgMap = new HashMap<String, Object>();\r";
		for (int i = 0; i < lf.size(); i++) {
			FieldData fieldData = lf.get(i);
			updText += "\t\t valueArgMap.put(\""+fieldData.getField()+"\", "+classNameLowerCase+".get"+DomysqlBean.replaceLine(DomysqlBean.toUpperCaseFirstOne(fieldData.getField()))+"());\r";
		}

		updText += "\t\t return update(\""+classNameLowerCase+"\", valueArgMap);\r";
		updText += "\t}\r";
		System.out.println(updText);
		return updText;
	}

	public static String generateSelectText(String className)  {
		String selectText = "";

		selectText+="\r\tpublic List<"+className+"> select() {\r";
		selectText+="\r\t\tString sql = \"SELECT * from "+tableName+" \";\r";
		selectText+="\t	List<"+className+"> query = namedParameterJdbcTemplate.query(sql, \r";
		selectText+="\t			new RowMapper() {                                      \r";
		selectText+="\t				@Override                                          \r";
		selectText+="\t				public "+className+" mapRow(ResultSet rs, int rowNum) \r";
		selectText+="\t						throws SQLException {                      \r";
		selectText+="\t\t\t\t\t\t\t"+className+" "+classNameLowerCase+" = new "+className+"();         \r";

		for (int i = 0; i < lf.size(); i++) {
			FieldData fieldData = lf.get(i);
			String filed = DomysqlBean.replaceLine(DomysqlBean.toUpperCaseFirstOne(fieldData.getField()));
			String dataType=DomysqlBean.gettypestring(fieldData.getDatatype());
			if("Integer".equals(dataType)){
				dataType="Int";
			}
			selectText +="\t\t\t\t\t\t\t"+classNameLowerCase+".set"+filed+"(rs.get"+dataType+"(\""+fieldData.getField()+"\"));       \r";
		}


		selectText+="\t					return "+classNameLowerCase+";            \r";
		selectText+="\t				}                                                  \r";
		selectText+="\t			});                                                    \r";
        selectText+=" \t                                                                 \r";
		selectText+="\t	return query;                                                  \r";
		selectText+="\t}                                                                 \r";
		return selectText;
	}

	public static String controller(String className) {
		String text = "";
		text += "package cn.lebaodai.lbd.controller;                                 \r";
		text += "import org.springframework.beans.factory.annotation.Autowired;      \r";
		text += "import org.springframework.beans.factory.annotation.Qualifier;      \r";
		text += "import org.springframework.stereotype.Controller;                   \r";
		text += "import org.springframework.web.bind.annotation.RequestMapping;      \r";
		text += "import cn.lebaodai.lbd.service.I" + className
				+ "Service; 				\r";
		text += "import cn.lebaodai.lbd.service.impl." + className
				+ "Service; 			\r";
		text += "import cn.lebaodai.lbd.vo." + className + "; 							\r";
		text += "/**                                                                 \r";
		text += " *                                                                  \r";
		text += " *                                                                  \r";
		text += " * @author kanghong                                                 \r";
		text += " * @version 0.0.1                                                   \r";
		text += " * @since                                                           \r";
		text += " */                                                                 \r";
		text += "@Controller                                                         \r";
		text += "@RequestMapping(\"/" + classNameLowerCase
				+ "\")                   \r";
		text += "public class " + className
				+ "Controller   extends EntityController<" + className + ", "
				+ className + "Service>  {                              \r";
		text += "                                                                    \r";
		text += "	@Autowired                                                         \r";
		text += "	@Qualifier(\"" + classNameLowerCase
				+ "Service\")                 \r";
		text += "	private I" + className + "Service " + classNameLowerCase
				+ "Service;  \r";
		text += "                                                                    \r";
		text += "                                                                    \r";
		text += "}                                                                   \r";

		return text;
	}

	public static String IDaoBean(String className) {
		String text = "";
		text += "package cn.lebaodai.lbd.dao;                                \r";
		text += "import java.util.List;                               		 \r";
		text += "import cn.lebaodai.lbd.vo." + className
				+ ";                    \r";
		text += "/**                                                         \r";
		text += " *                                                          \r";
		text += " *                                                          \r";
		text += " * @author  kanghong                                        \r";
		text += " * @version 0.0.1                                           \r";
		text += " * @since                                                   \r";
		text += " */                                                         \r";
		text += "public interface I" + className + "Dao extends IEntityDao<"+ className + "> {        \r";
		text += "	                                                           \r";
		text += "\t public long add(" + className + " " + classNameLowerCase + ");                                  \r";
		text += "\t public long upd(" + className + " " + classNameLowerCase + ");                                  \r";
		text += "\t public List<" + className + "> select();                                    \r";
		text += "}                                                            \r";
		return text;
	}

	public static String IDaoImplBean(String className) {
		String text = "";
		text += "package cn.lebaodai.lbd.dao.impl;                                \r";
		text += "import java.util.HashMap; \r";
		text += "import java.util.Map; \r";
		text += "import java.sql.ResultSet;                                      \r";
		text += "import java.sql.SQLException;                                   \r";
		text += "import java.util.List;                                          \r";
		text += "import org.springframework.jdbc.core.RowMapper;   \r";
		text += "import org.springframework.beans.factory.annotation.Qualifier;   \r";
		text += "import org.springframework.stereotype.Repository;                \r";
		text += "import cn.lebaodai.lbd.dao.I" + className
				+ "Dao;                      \r";
		text += "import cn.lebaodai.lbd.vo." + className
				+ ";                           \r";
		text += "/**                                                              \r";
		text += " *                                                               \r";
		text += " * @author kanghong                                              \r";
		text += " * @version 0.0.1                                                \r";
		text += " * @since 	                                                    \r";
		text += " */                                                              \r";
		text += "@Repository                                                      \r";
		text += "@Qualifier(\"" + classNameLowerCase + "Dao"
				+ "\")                                     \r";
		text += "public class " + className + "Dao extends EntityDao<"
				+ className + "> implements I" + className + "Dao {\r";
		text += "\t@Override ";
		text += generateAddText(className);
		text += "\t@Override ";
		text += generateUpdText(className);
		text += "\t@Override \r";
		text += generateSelectText(className);
		text += "	                                                           \r     \r";
		text += "}";
		return text;
	}

	public static String IServiceBean(String className) {
		String text = "";
		text += "package cn.lebaodai.lbd.service;                                \r";
		text += "import java.util.List;                               		 \r";
		text += "import cn.lebaodai.lbd.vo." + className
				+ ";                    \r";
		text += "/**                                                         \r";
		text += " *                                                          \r";
		text += " *                                                          \r";
		text += " * @author  kanghong                                        \r";
		text += " * @version 0.0.1                                           \r";
		text += " * @since                                                   \r";
		text += " */                                                         \r";
		text += "public interface I" + className
				+ "Service  {                   \r";
		text += "	                                                           \r";
		text += "\t public long add(" + className + " " + classNameLowerCase + ");                                  \r";
		text += "\t public long upd(" + className + " " + classNameLowerCase + ");                                  \r";
		text += "\t public List<" + className + "> select();                                    \r";
		text += "}                                                            \r";
		return text;
	}

	public static String IServiceImplBean(String className) {
		String text = "";
		text += "package cn.lebaodai.lbd.service.impl;                            \r";
		text += "import java.util.List;                               		 \r";
		text += "import org.springframework.beans.factory.annotation.Autowired;   \r";
		text += "import org.springframework.beans.factory.annotation.Qualifier;   \r";
		text += "import org.springframework.stereotype.Service;                   \r";
		text += "import cn.lebaodai.lbd.dao.I" + className
				+ "Dao;                         \r";
		text += "import cn.lebaodai.lbd.dao.impl." + className
				+ "Dao;                     \r";
		text += "import cn.lebaodai.lbd.service.I" + className
				+ "Service;                 \r";
		text += "import cn.lebaodai.lbd.vo." + className
				+ ";                              \r";
		text += "/**                                                              \r";
		text += " *                                                               \r";
		text += " *                                                               \r";
		text += " * @author kanghong                                              \r";
		text += " * @version 0.0.1                                                \r";
		text += " * @since                                                        \r";
		text += " */                                                              \r";
		text += "@Service                                                         \r";
		text += "@Qualifier(\"" + classNameLowerCase
				+ "Service\")                                    \r";
		text += "public class " + className + "Service extends EntityService<"
				+ className + ", " + className + "Dao>    \r";
		text += "		implements I" + className + "Service {    \r";
		text += "	@Autowired    \r";
		text += "	@Qualifier(\"" + classNameLowerCase + "Dao\")    \r";
		text += "	private I" + className + "Dao " + classNameLowerCase
				+ "Dao;    \r";
		text += "	                                                           \r";
		text += "\t@Override                                       \r";
		text += "\tpublic long add(" + className + "  " + classNameLowerCase + ") {                \r";
//		text += "\t	// TODO Auto-generated method stub           \r";
		text += "\t	return  " + classNameLowerCase + "Dao.add( " + classNameLowerCase + ");                \r";
		text += "\t}                                               \r";
        text += "\t                                                \r";
		text += "\t@Override                                       \r";
		text += "\tpublic long upd(" + className + "  " + classNameLowerCase + ") {                \r";
//		text += "\t	// TODO Auto-generated method stub           \r";
		text += "\t	return  " + classNameLowerCase + "Dao.upd( " + classNameLowerCase + ");                \r";
		text += "\t}                                               \r";
        text += "\t                                                \r";
		text += "\t@Override                                       \r";
		text += "\tpublic List<" + className + "> select() {                  \r";
//		text += "\t	// TODO Auto-generated method stub           \r";
		text += "\t	return  " + classNameLowerCase + "Dao.select();                   \r";
		text += "\t}                                               \r";

		text += "}    \r";
		return text;
	}

	public static void saveFile(String classname, String text, String pageName) {

		System.out.println("text:" + text);
		System.out.println("创建java类：" + classname);
		String filepath = Thread.currentThread().getContextClassLoader()
				.getResource(".").getPath();

		System.out.println("filepath:" + filepath);
		// LOG.out(filepath);

		String[] fileP = filepath.split("target");
		System.out.println(fileP[0]);

		File file = new File(fileP[0] + "/src/main/java/cn/lebaodai/lbd/"
				+ pageName + "/" + FormData.firstUpper(classname) + ".java");
		/*
		 * File file = new File(
		 * "F\:\lebaodai\myelicpseWs\trunk\src\main\java\cn\lebaodai\lbd\vo\Msg_push.java");
		 */

		if (file.exists()) {
			file.delete();
		}

		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdir();
		}

		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		BufferedWriter writer;
		try {
			writer = new BufferedWriter(
					new FileWriter(new File(file.getPath())));
			writer.write(text);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
